package com.example.usbprinter;

import android.app.Application;
import android.content.Context;
import android.content.IntentFilter;
import android.hardware.usb.UsbManager;
import android.util.Log;

import com.epson.epos2.discovery.DeviceInfo;
import com.epson.epos2.discovery.Discovery;
import com.epson.epos2.discovery.DiscoveryListener;
import com.epson.epos2.discovery.FilterOption;
import com.epson.epos2.printer.Printer;

import androidx.annotation.NonNull;

public class USBPrinter {

    private static Application sApplication;
    private static Printer mPrinter;

    /**
     * 初始化
     *
     * @param app Application
     */
    public static void init(@NonNull final Application app) {
        if (sApplication == null) {
            USBPrinter.sApplication = app;
            register(app);
        }
    }

    /**
     * 注册USB插入和拔出监听
     *
     * @param context Context
     */
    public static void register(Context context) {
        IntentFilter filter = new IntentFilter();
        filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
        USBBroadCastReceiver usbBroadCastReceiver = new USBBroadCastReceiver();
        context.registerReceiver(usbBroadCastReceiver, filter);
        startDiscovery(context);
    }


    /**
     * 打印机设备监听器
     */
    private static final DiscoveryListener mDiscoveryListener = new DiscoveryListener() {
        @Override
        public void onDiscovery(final DeviceInfo deviceInfo) {
            try {
                mPrinter = new Printer(Printer.TM_T100, Printer.MODEL_ANK, sApplication);
                mPrinter.connect(deviceInfo.getTarget(), Printer.PARAM_DEFAULT);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    /**
     * 获取打印机对象，null表示打印机未连接或者还没初始化完成
     *
     * @return Printer
     */
    public static Printer getPrinter() {
        return mPrinter;
    }


    /**
     * 开启打印机设备连接检测
     *
     * @param context Context
     */
    public static void startDiscovery(Context context) {
        FilterOption filterOption = new FilterOption();
        filterOption.setPortType(Discovery.PORTTYPE_USB);
//        filterOption.setBroadcast("255.255.255.255");
        filterOption.setDeviceModel(Discovery.MODEL_ALL);
        filterOption.setEpsonFilter(Discovery.FILTER_NAME);
        filterOption.setDeviceType(Discovery.TYPE_ALL);
        try {
            Discovery.start(context, filterOption, mDiscoveryListener);
        } catch (Exception e) {
            Log.e("USBPrinter", "start_Exception" + e.toString());
        }
    }

    /**
     * 停止打印连接检测
     */
    public static void stopDiscovery() {
        try {
            Discovery.stop();
            if (mPrinter != null) {
                mPrinter.disconnect();
                mPrinter = null;
            }
        } catch (Exception e) {
            Log.e("USBPrinter", "stop_Exception" + e.toString());
        }
    }
}
